package com.blog.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.blog.common.EasyUITree;
import com.blog.dao.MCategoryMapper;
import com.blog.pojo.MCategory;
import com.blog.pojo.MCategoryExample;
import com.blog.pojo.MCategoryExample.Criteria;
import com.blog.service.ICategoryService;

@Service
public class CategoryService implements ICategoryService {
	
	
	@Autowired
	private MCategoryMapper catMapper;
	
	
	
	//easy ui tree 得到品类目录
	@Override
	public List<EasyUITree> getTreeCategory(int id) {
		
		// 根据parentId查询分类列表
		MCategoryExample example = new MCategoryExample();
		Criteria criteria = example.createCriteria();
		criteria.andParentidEqualTo(id);
		
		List<MCategory> lists = catMapper.selectByExample(example);
		
		//转化成EasyUITree列表
		List<EasyUITree> Treelist = new ArrayList<>();
			
			for (MCategory cat : lists) {
				
				EasyUITree tree = new EasyUITree();
				tree.setId(cat.getId());
				tree.setState(cat.getIsParent()?"closed":"open");
				//System.out.println(cat.getIsParent());
				
				tree.setText(cat.getName());
				Treelist.add(tree);
			}
			
			return Treelist;
	}


	@Override
	public Map addCategory(Integer parentId, String name) {
		
		
		Map map = new HashMap();
		
		MCategory category = new MCategory();
		
		//预留字段， 现在不考虑子目录
		//category.setParentid(parentId);
		category.setParentid(0);
		category.setIsParent(false);
		category.setName(name);
		category.setStatus(true); 
		category.setCreated(new Date());
		category.setUpdated(new Date());
		int res = catMapper.insert(category );
		if(res == 1){
			map.put("status", 0);
			map.put("data", category.getId());
			System.out.println(category.getId());
		}else{
			map.put("status", 1);
		}
		
		return map;
	}


	@Override
	public Map updateCategory(Integer id, String name) {
		
		Map map = new HashMap();
		
		int res = catMapper.updateNameById(id,name);
		
		if(res == 1){
			map.put("status", 0);
		}else{
			map.put("status", 1);
		}
		
		return map;
	}


	@Override
	public Map delete(Integer parentId, Integer id) {
		
		Map map = new HashMap();
		
		//根据主键删除
		int res = catMapper.deleteByPrimaryKey(id);
		
		if(res == 1){
			map.put("status", 0);
		}else{
			map.put("status", 1);
		}
		
		return map;
	}
		
}	
